package win.larryzeal.spring.web.advice;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.fasterxml.jackson.databind.ObjectMapper;

import win.larryzeal.spring.except.BizException;
import win.larryzeal.spring.util.MyResult;

/**
 * 第二个测试
 * 
 * @author LarryZeal
 *
 */
@ControllerAdvice
public class WebExceptionHandler {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@ExceptionHandler({ ServletException.class })
	public void http404(HttpServletRequest request, HttpServletResponse response, ServletException e)
			throws IOException {
		logger.error("HttpRequest error:{}", request.getRequestURL());
		logger.error("HttpRequest error stack :", e);
		outputMessage(response, HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase());
	}

	@ExceptionHandler(BizException.class)
	public void handleBizException(HttpServletRequest request, HttpServletResponse response, BizException e)
			throws IOException {
		logger.error("Biz error occurs during :{}", request.getRequestURI());
		logger.error("Biz error stack :", e);
		outputMessage(response, HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
	}

	@ExceptionHandler({ Error.class, Exception.class, Throwable.class })
	public void exception(HttpServletRequest request, HttpServletResponse response, Throwable e) throws IOException {
		logger.error("Unknown error occurs during :{}", request.getRequestURI());
		logger.error("Unknown system error stack:", e);
		outputMessage(response, HttpStatus.SERVICE_UNAVAILABLE.value(), HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase());
	}

	/**
	 * 
	 * @param response
	 * @param errCode
	 * @param errMsg
	 * @throws IOException
	 */
	private void outputMessage(HttpServletResponse response, Integer errCode, String errMsg) throws IOException {
		MyResult result = MyResult.failResult(errCode, errMsg);
		// String json = JsonMapper.toJson(result);
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(result);

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		response.setStatus(500);
		response.sendError(403, "禁止访问"); // TODO: 至此，response已经结束，后面的代码应该无效的
		ServletOutputStream os = response.getOutputStream();
		os.write(json.getBytes("utf-8"));
	}
}